// pages/canvas-test/canvas-test.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onReady: function (options) {
    wx.createSelectorQuery()
      .select('#canvas')
      .fields({
        node: true,
        size: true,
      })
      .exec(this.init.bind(this))
  },

  async init(res) {
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    const ctx = canvas.getContext('2d')

    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr)

    this.canvas = canvas

    this.fillRoundRect(ctx, 0, 0, width, height, 15, '#fff')

    await this.drawBg(canvas, ctx, width) // 绘制背景图
    await this.drawAvatar(canvas, ctx) // 绘制头像

    // 绘制邀请码文本
    ctx.fillStyle = "#2458ce";
    ctx.font = "18px sans-serif";
    ctx.fillText("邀请码：1256489", 92, 410);

    // 绘制姓名文本
    ctx.fillStyle = "#fff";
    // ctx.font = "18px sans-serif";
    ctx.fillText("胡小洋", 110, 106);

    // 绘制电话号码文本
    // ctx.font = "18px sans-serif";
    ctx.fillText("13688897789", 104, 132);

    // 绘制文本
    ctx.fillStyle = "#000";
    ctx.font = "12px sans-serif";
    ctx.fillText("分享给好友", 61, 504);
    ctx.fillText("保存到相册", 196, 504);

    this.drawQRCode(canvas, ctx)
    this.drawWXIcon(canvas, ctx) // 绘制微信分享图标
    this.drawSaveIcon(canvas, ctx) // 绘制保存图标
  },

  drawBg(canvas, ctx, width) {
    return new Promise((resolve, reject) => {
      const img = canvas.createImage()
      img.onload = () => {
        const imgRatio = img.height / img.width
        ctx.drawImage(img, 0, 0, width, width * imgRatio)
        resolve()
      }
      img.src = '../../image/invitation-bg.png'
    })

  },
  drawAvatar(canvas, ctx) {
    return new Promise((resolve, reject) => {
      const img = canvas.createImage()
      img.onload = () => {
        ctx.drawImage(img, 29, 77, 65, 65)
        resolve()
      }
      img.src = '../../image/home-s2.png'
    })
  },
  drawWXIcon(canvas, ctx) {
    return new Promise((resolve, reject) => {
      const img = canvas.createImage()
      img.onload = () => {
        ctx.drawImage(img, 66, 436, 50, 50)
        resolve()
      }
      img.src = '../../image/share.png'
    })
  },
  drawSaveIcon(canvas, ctx) {
    return new Promise((resolve, reject) => {
      const img = canvas.createImage()
      img.onload = () => {
        ctx.drawImage(img, 201, 436, 50, 50)
        resolve()
      }
      img.src = '../../image/save.png'
    })
  },
  drawQRCode(canvas, ctx) {
    return new Promise((resolve, reject) => {
      const img = canvas.createImage()
      img.onload = () => {
        ctx.drawImage(img, 75, 210, 175, 175)
        resolve()
      }
      img.src = '../../image/qr-code.png'
    })
  },

  /**该方法用来绘制圆角矩形 
   *@param cxt:canvas的上下文环境 
   *@param x:左上角x轴坐标 
   *@param y:左上角y轴坐标 
   *@param width:矩形的宽度 
   *@param height:矩形的高度 
   *@param radius:圆的半径 
   *@param lineWidth:线条粗细 
   *@param strokeColor:线条颜色 
   **/
  strokeRoundRect: function (cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
    //圆的直径必然要小于矩形的宽高          
    if (2 * radius > width || 2 * radius > height) { return false; }

    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边  
    this.drawRoundRectPath(cxt, width, height, radius);
    cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2  
    cxt.strokeStyle = strokeColor || "#000";
    cxt.stroke();
    cxt.restore();
  },
  drawRoundRectPath: function (cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI  
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

    //矩形下边线  
    cxt.lineTo(radius, height);

    //左下角圆弧，弧度从1/2PI到PI  
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

    //矩形左边线  
    cxt.lineTo(0, radius);

    //左上角圆弧，弧度从PI到3/2PI  
    cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

    //上边线  
    cxt.lineTo(width - radius, 0);

    //右上角圆弧  
    cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

    //右边线  
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  },

  /**该方法用来绘制一个有填充色的圆角矩形 
     *@param cxt:canvas的上下文环境 
     *@param x:左上角x轴坐标 
     *@param y:左上角y轴坐标 
     *@param width:矩形的宽度 
     *@param height:矩形的高度 
     *@param radius:圆的半径 
     *@param fillColor:填充颜色 
     **/
  fillRoundRect: function (cxt, x, y, width, height, radius, /*optional*/ fillColor) {
    //圆的直径必然要小于矩形的宽高          
    if (2 * radius > width || 2 * radius > height) { return false; }

    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边  
    this.drawRoundRectPath(cxt, width, height, radius);
    cxt.fillStyle = fillColor || "#000"; //若是给定了值就用给定的值否则给予默认值  
    cxt.fill();
    cxt.restore();
  },

  onSave() {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      canvas: this.canvas,
      success: res => {
        this.saveImg(res.tempFilePath)
      },
      fail: function (res) {
        console.log('fail', res)
      }
    })
  },
  // 长按保存事件
  saveImg(filePath) {
    let that = this;

    function saveImage () {
      wx.saveImageToPhotosAlbum({
        filePath,
        success() {
          wx.showToast({
            title: '保存成功'
          })
        },
        fail() {
          wx.showToast({
            title: '保存失败',
            icon: 'none'
          })
        }
      })
    }

    // 获取用户是否开启用户授权相册
    wx.getSetting({
      success(res) {
        // 如果没有则获取授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              saveImage()
            },
            fail() {
              // 如果用户拒绝过或没有授权，则再次打开授权窗口
              //（ps：微信api又改了现在只能通过button才能打开授权设置，以前通过openSet就可打开，下面有打开授权的button弹窗代码）
              // that.setData({
              //   openSet: true
              // })
            }
          })
        } else {
          // 有则直接保存
          saveImage()
        }
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})